package com.hellobike.haxing.modules.wms.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.hellobike.haxing.common.system.vo.LoginUser;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.util.oConvertUtils;
import com.hellobike.haxing.modules.product.controller.SkuController;
import com.hellobike.haxing.modules.product.entity.Sku;
import com.hellobike.haxing.modules.product.service.ISkuService;
import com.hellobike.haxing.modules.wms.dto.AsnHeaderDto;
import com.hellobike.haxing.modules.wms.dto.ExportAsnDto;
import com.hellobike.haxing.modules.wms.dto.SkuDto;
import com.hellobike.haxing.modules.wms.entity.AsnDetail;
import com.hellobike.haxing.modules.wms.entity.AsnHeader;
import com.hellobike.haxing.modules.wms.exception.WmsExportException;
import com.hellobike.haxing.modules.wms.exception.WmsServiceException;
import com.hellobike.haxing.modules.wms.facade.WmsExportFacade;
import com.hellobike.haxing.modules.wms.facade.WmsReceiveFacade;
import com.hellobike.haxing.modules.wms.service.IAsnHeaderService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.modules.wms.service.IWarehouseDepartService;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import com.hellobike.haxing.common.system.base.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.hellobike.haxing.common.annotation.AutoLog;

/**
* @Description: t_wms_asn_header
* @Author: haxing-boot
* @Date:   2020-01-09
* @Version: V1.0
*/
@RestController
@RequestMapping("/wms/asnHeader")
@Slf4j
public class AsnHeaderController extends WmsBaseController<AsnHeader, IAsnHeaderService> {
   @Autowired
   private IAsnHeaderService asnHeaderService;

   @Autowired
   private WmsReceiveFacade wmsReceiveFacade;

   /**
    * 分页列表查询
    *
    * @param asnHeader
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @AutoLog(value = "t_wms_asn_header-分页列表查询")
   @GetMapping(value = "/list")
   public Result<?> queryPageList(AsnHeader asnHeader,
                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                  HttpServletRequest req) {
       LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
       Integer userId = sysUser.getId();
       Long warehouseId = getWarehouseId();
       log.info("======================>sysUser;"+sysUser);
       log.info("======================>warehouseId;"+warehouseId);
       asnHeader.setWarehouseId(warehouseId);
       QueryWrapper<AsnHeader> queryWrapper = QueryGenerator.initQueryWrapper(asnHeader, req.getParameterMap());
       Page<AsnHeader> page = new Page<AsnHeader>(pageNo, pageSize);
       page.addOrder(OrderItem.desc("id"));
       IPage<AsnHeader> pageList = asnHeaderService.page(page, queryWrapper);
       return Result.ok(pageList);
   }

   /**
    *   添加
    *
    * @param json
    * @return
    */
   /*
{"asnDetails":[{"skuId":5,"skuCode":"12345","skuName":"商品05","qty":"2131"},
{"skuId":6,"skuCode":"12346","skuName":"商品06","qty":"23432"}],
"asnHeader":{"refOrderId":"1234","refOrderCode":"1113333","supplierId":1,
"exptArriveTime":"2020-01-30 17:05:17","tel":"111","concatName":"111"}}
    */
   @AutoLog(value = "t_wms_asn_header-添加",operateType=2)
   @PostMapping(value = "/add")
   public Result<?> add(@RequestBody JSONObject json) {
       log.info(json.toJSONString());
       try {
           AsnHeader header = new AsnHeader();
           header.setRefOrderId(json.getJSONObject("asnHeader").getLong("refOrderId"));
           header.setRefOrderCode(json.getJSONObject("asnHeader").getString("refOrderCode"));
           header.setSupplierId(json.getJSONObject("asnHeader").getLong("supplierId"));
           header.setExptArriveTime(json.getJSONObject("asnHeader").getDate("exptArriveTime"));
           header.setTel(json.getJSONObject("asnHeader").getString("tel"));
           header.setConcatName(json.getJSONObject("asnHeader").getString("concatName"));
           List<AsnDetail> details = new ArrayList<>();
           JSONArray asnDetails = json.getJSONArray("asnDetails");
           for (int i = 0; i < asnDetails.size(); i++) {
               JSONObject detailJson = asnDetails.getJSONObject(i);
               AsnDetail detail = new AsnDetail();
               detail.setSkuId(detailJson.getLong("skuId"));
               detail.setPurchaseCount(detailJson.getBigDecimal("qty"));
               details.add(detail);
           }
           LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
           Integer userId = sysUser.getId();
           Long warehouseId = getWarehouseId();
           log.info("======================>warehouseId;"+warehouseId);
           wmsReceiveFacade.addAsnByHand(header,details,warehouseId,userId);
       } catch (Exception e) {
           log.error("",e);
           return Result.error(e.getMessage());
       }
       return Result.ok("添加成功！");
   }

   /**
    *  编辑
    *
    * @param asnHeader
    * @return
    */
   @AutoLog(value = "t_wms_asn_header-编辑",operateType=3)
   @PutMapping(value = "/edit")
   public Result<?> edit(@RequestBody AsnHeader asnHeader) {
       asnHeaderService.updateById(asnHeader);
       return Result.ok("编辑成功!");
   }

   /**
    *   通过id删除
    *
    * @param id
    * @return
    */
   @AutoLog(value = "t_wms_asn_header-删除",operateType=4)
   @DeleteMapping(value = "/delete")
   public Result<?> delete(@RequestParam(name="id",required=true) String id) {
       asnHeaderService.removeById(id);
       return Result.ok("删除成功!");
   }

   /**
    *  批量删除
    *
    * @param ids
    * @return
    */
   @AutoLog(value = "t_wms_asn_header-批量删除",operateType=4)
   @DeleteMapping(value = "/deleteBatch")
   public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       this.asnHeaderService.removeByIds(Arrays.asList(ids.split(",")));
       return Result.ok("批量删除成功!");
   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   @GetMapping(value = "/queryById")
   public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
       AsnHeader asnHeader = asnHeaderService.getById(id);
       if(asnHeader==null) {
           return Result.error("未找到对应数据");
       }
       return Result.ok(asnHeader);
   }
   /**
   * 导出excel
   *
   */
   @AutoLog(value = "t_wms_asn_header-导出excel",operateType=6)
   @RequestMapping(value = "/exportXls")
   public ModelAndView exportXls(@RequestParam Long id) throws WmsExportException {
       try {
           AsnHeader asnHeader = asnHeaderService.getById(id);
           String title = "收货-"+asnHeader.getAsnCode();
           List<ExportAsnDto> exportList = wmsExportFacade.exportAsn(id);
           return export(title,ExportAsnDto.class,exportList);
       } catch (Exception e) {
           throw new WmsExportException(e);
       }
   }

   /**
     * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
   @AutoLog(value = "t_wms_asn_header-导入excel",operateType=5)
   @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
   public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
       return super.importExcel(request, response, AsnHeader.class);
   }


    @AutoLog(value = "t_wms_asn_header-详情页查询")
    @PostMapping(value = "/detail")
    public Result<?> queryDetail(@RequestBody JSONObject json,
                                   HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Integer userId = sysUser.getId();
        Long warehouseId = getWarehouseId();
        log.info("======================>sysUser;"+sysUser);
        log.info("======================>warehouseId;"+warehouseId);
        Long headerId = json.getLong("headerId");
        AsnHeaderDto asnHeaderDto = null;
        try {
            asnHeaderDto = wmsReceiveFacade.queryAsnInfo(headerId,warehouseId);
        } catch (WmsServiceException e) {
            return Result.error(e.getMessage());
        }
        return Result.ok(asnHeaderDto);
    }


    @AutoLog(value = "t_wms_asn_header-分页列表查询")
    @GetMapping(value = "/querySku")
    public Result<?> querySkuList(
                                    @RequestParam(name="barCode", required = false) String barCode,
                                   HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Integer userId = sysUser.getId();
        Long warehouseId = getWarehouseId();
        log.info("======================>sysUser;"+sysUser);
        log.info("======================>warehouseId;"+warehouseId);
        List<SkuDto> skuDtos = null;
        try {
            skuDtos = wmsReceiveFacade.querySkuByBarCode(barCode);
        } catch (WmsServiceException e) {
            return Result.error(e.getMessage());
        }
        return Result.ok(skuDtos);
    }

    @AutoLog(value = "t_wms_asn_header-收货")
    @PostMapping(value = "/received")
    public Result<?> received(@RequestBody JSONObject json,
                                 HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Integer userId = sysUser.getId();
        Long warehouseId = getWarehouseId();
        log.info("======================>sysUser;"+sysUser);
        log.info("======================>warehouseId;"+warehouseId);
        Long headerId = json.getLong("headerId");
        try {
            String opName = json.getString("opName");
            if(StringUtils.isEmpty(opName)){
                throw new WmsServiceException("请输入操作人");
            }
            List<AsnDetail> details = JSON.parseArray(json.getJSONArray("data").toJSONString(),AsnDetail.class);
            wmsReceiveFacade.receiveAsn(details,headerId,opName,warehouseId,userId);
        } catch (WmsServiceException e) {
            return Result.error(e.getMessage());
        }
        return Result.ok();
    }



}
